package com.neusoft.neumooc.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.minidev.json.JSONObject;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.neusoft.core.util.jwt.Jwt;
import com.neusoft.core.util.jwt.TokenState;

/**
 * @ClassName: LoginInterceptor
 * @Description: TODO 拦截器控制类
 * @author zls
 * @date 2016年11月4日
 */
public class LoginInterceptor implements HandlerInterceptor {

	/**
	 * @Title: afterCompletion
	 * @Description: TODO
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 * @throws Exception
	 */
	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	/**
	 * @Title: postHandle
	 * @Description: TODO
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 * @throws Exception
	 */
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
	}

	/**
	 * @Title: preHandle
	 * @Description: TODO 拦截除登录以外的其他功能，需登录才能进入其他页面
	 * @param request
	 * @param response
	 * @param arg2
	 * @return boolean
	 * @throws Exception
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object arg2) throws Exception {
		// 其他API接口一律校验token
		System.out.println("开始校验token");
		// 从请求头中获取token
		String token = request.getHeader("token");
		System.out.println("拦截器token:" + token);
		Map<String, Object> resultMap = Jwt.validToken(token);
		TokenState state = TokenState.getTokenState((String) resultMap
				.get("state"));

		switch (state) {
		case VALID:
			// 取出payload中数据,放入到request作用域中
			request.setAttribute("data", resultMap.get("data"));
			System.out.println("放行");
			// 放行
			return true;
		case EXPIRED:
		case INVALID:
			System.out.println("无效token");
			// token过期或者无效，则输出错误信息返回给ajax
			JSONObject outputMSg = new JSONObject();
			outputMSg.put("success", false);
			outputMSg.put("msg", "您的token不合法或者过期了，请重新登陆");
			System.out.println(outputMSg.toJSONString());
			break;
		}
		return false;
	}
}
